#include <LiquidCrystal.h>
LiquidCrystal lcd(8, 9, 4, 5, 6, 7);

byte sensorInterrupt = 0;
byte sensorPin = 2;
byte testoso = 3;
byte statusLed = 13;

float calibrationFactor = 7.5;

volatile byte pulseCount;

float flowRate;
unsigned int flowMilliLitres;
unsigned long totalMilliLitresA;
unsigned long totalMilliLitresB;
unsigned long oldTime;

int botoes = A0; //Analógico dos botoes
int valorbotoes = 0;
int resetButtonA = 0;
int resetButtonB = 0;

void setup() //
{ 
 lcd.begin(16, 2);
lcd.setCursor(0, 0);
lcd.print(" ");
lcd.setCursor(0, 1);
lcd.print(" "); 

 Serial.begin(9600);
 
 pinMode(sensorPin, INPUT);
digitalWrite(sensorPin, HIGH);

 pinMode(testoso, INPUT);
digitalWrite(testoso, HIGH);

pulseCount = 0;
flowMilliLitres = 0;
totalMilliLitresA = 0;
totalMilliLitresB = 0;
oldTime = 0;
 
attachInterrupt(sensorInterrupt, pulseCounter, FALLING);
}


void loop ()    
{
valorbotoes = analogRead(botoes);
if (valorbotoes <500)
{
 resetButtonB=1;
 resetButtonA=0;
}
else if (valorbotoes < 800)
{
 resetButtonA=1;
 resetButtonB=0; // do Thing B
}
else if (valorbotoes >= 1000)
{
 resetButtonA=0;
 resetButtonB=0; // do Thing B
}
else
{
 resetButtonA=0;
 resetButtonB=0;
}

if(resetButtonA == 1)
{
totalMilliLitresA = 0;
lcd.setCursor(0, 1);
lcd.print("0L ");
}
if(resetButtonB == 1)
{
totalMilliLitresB = 0;
lcd.setCursor(8, 1);
lcd.print("0L ");
}

if((millis() - oldTime) > 1000)
{
  detachInterrupt(sensorInterrupt);
  flowMilliLitres = pulseCount * (1000/(calibrationFactor*60));
  flowRate = (flowMilliLitres * (60000 / (millis() - oldTime))) / 1000;
  totalMilliLitresA += flowMilliLitres;
  totalMilliLitresB += flowMilliLitres;
Serial.print(pulseCount, DEC);
Serial.print(" ");
  
  unsigned int frac;
  
  Serial.print(int(flowRate));
  Serial.print(".");
  
  frac = (flowRate - int(flowRate)) * 10;
  Serial.print(frac, DEC);
  
  Serial.print(" ");
Serial.print(flowMilliLitres);
Serial.print(" ");
Serial.print(totalMilliLitresA);
Serial.print(" ");
Serial.println(totalMilliLitresB);
Serial.print("Sensor ");
Serial.println(digitalRead(testoso));



lcd.setCursor(0, 0);
lcd.print(" ");
lcd.setCursor(0, 0);
lcd.print("Fluxo ");

if(int(flowRate) < 10)
{
lcd.print(" ");
}

lcd.print((int)flowRate);
lcd.print('.');
lcd.print(frac, DEC);
lcd.print(" L/min");

lcd.setCursor(0, 1);
lcd.print(int(totalMilliLitresA));
lcd.print("mL");
lcd.setCursor(8, 1);
lcd.print(int(totalMilliLitresB / 1000));
lcd.print("L");

pulseCount = 0;

oldTime = millis();

attachInterrupt(sensorInterrupt, pulseCounter, FALLING);
}
}

void pulseCounter()
{
pulseCount++;
}




